<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-steps :active="currentTab" align-center finish-status="success">
          <el-step title="选择商品"/>
          <el-step title="填写进货单"/>
        </el-steps>
      </div>
      <el-form ref="formValidate" v-loading="fullscreenLoading" class="formValidate mt20" :rules="ruleValidate"
               :model="formValidate" label-width="160px" @submit.native.prevent
      >
        <div v-show="currentTab === 0" style="overflow: hidden;">
          <el-row :gutter="24">
            <el-col v-bind="grid2">
              <el-form-item label="选择商品：" prop="image">
                <div class="upLoadPicBox" @click="add()">
                  <div v-if="formValidate.image" class="pictrue">
                    <img :src="formValidate.image">
                  </div>
                  <div v-else class="upLoad">
                    <i class="el-icon-camera cameraIconfont"/>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-show="currentTab === 1">
          <el-row :gutter="24">
            <el-col v-bind="grid2">
              <el-form-item label="商品主图：" prop="image">
                <div class="upLoadPicBox">
                  <div v-if="formValidate.image" class="pictrue">
                    <img :src="formValidate.image">
                  </div>
                  <div v-else class="upLoad">
                    <i class="el-icon-camera cameraIconfont"/>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="商品名称：">
                <el-input v-model="formValidate.store_name" readonly placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="进货单号：">
                <el-input v-model="formValidate.supplier_sn" placeholder="进货单号"/>
                <el-button class="mr15" size="small" @click="getSn">自动生成</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
              <!-- 单规格表格-->
              <el-form-item v-if="formValidate.spec_type === 0" label="规格列表：">
                <el-table :data="OneattrValue" border class="tabNumWidth" size="mini">
                  <el-table-column align="center" label="市场价" min-width="80">
                    <template slot-scope="scope">
                      <span>{{ scope.row['price'] }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="成本价" min-width="80">
                    <template slot-scope="scope">
                      <span>{{ scope.row['cost'] }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="库存" min-width="80">
                    <template slot-scope="scope">
                      <span>{{ scope.row['old_stock'] }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="商品编码" min-width="80">
                    <template slot-scope="scope">
                      <span>{{ scope.row['bar_code'] }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="销售价" min-width="80">
                    <template slot-scope="scope">
                      <el-input v-model.number=" scope.row['xh_price']" type="number" class="priceBox" :min="0"/>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="成本价" min-width="80">
                    <template slot-scope="scope">
                      <el-input v-model.number=" scope.row['cost_price']" type="number" class="priceBox" :min="0"/>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="进货数量" min-width="80">
                    <template slot-scope="scope">
                      <el-input v-model.number="scope.row['stock_num']" type="number" class="priceBox" :min="0"/>
                    </template>
                  </el-table-column>
                </el-table>
                <span class="item_desc">销售价和成本价为0不会修改商品价格</span>
              </el-form-item>
              <!-- 多规格表格-->
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-form-item v-if="formValidate.spec_type === 1" class="labeltop" label="规格列表：">
              <el-table ref="multipleSelection" :data="ManyAttrValue" tooltip-effect="dark"
                        :row-key="(row) => { return row.id }" @selection-change="handleSelectionChange"
              >
                <el-table-column align="center" type="selection" :reserve-selection="true" min-width="50"/>
                <template v-if="manyTabDate">
                  <el-table-column v-for="(item,iii) in manyTabDate" :key="iii" align="center"
                                   :label="manyTabTit[iii].title" min-width="80"
                  >
                    <template slot-scope="scope">
                      <span class="priceBox" v-text="scope.row[iii]"/>
                    </template>
                  </el-table-column>
                </template>
                <el-table-column align="center" label="市场价" min-width="80">
                  <template slot-scope="scope">
                    <span>{{ scope.row['price'] }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="成本价" min-width="80">
                  <template slot-scope="scope">
                    <span>{{ scope.row['cost'] }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="库存" min-width="80">
                  <template slot-scope="scope">
                    <span>{{ scope.row['old_stock'] }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="商品编码" min-width="80">
                  <template slot-scope="scope">
                    <span>{{ scope.row['bar_code'] }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="销售价" min-width="80">
                  <template slot-scope="scope">
                    <el-input v-model.number=" scope.row['xh_price']" type="number" class="priceBox" :min="0"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="成本价" min-width="80">
                  <template slot-scope="scope">
                    <el-input v-model.number=" scope.row['cost_price']" type="number" class="priceBox" :min="0"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="进货数量" min-width="80">
                  <template slot-scope="scope">
                    <el-input v-model.number="scope.row['stock_num']" type="number" class="priceBox" :min="0"/>
                  </template>
                </el-table-column>
              </el-table>
              <span class="item_desc">销售价和成本价为0不会修改商品价格</span>
            </el-form-item>
          </el-row>
        </div>
        <!-- 商品详情-->
        <el-form-item style="margin-top:30px;">
          <el-button v-show="currentTab>0" type="primary" class="submission" size="small" @click="handleSubmitUp">
            上一步
          </el-button>
          <el-button v-show="currentTab == 0" type="primary" class="submission" size="small"
                     @click="handleSubmitNest1('formValidate')"
          >下一步
          </el-button>
          <el-button v-show="currentTab===1" :loading="loading" type="primary" class="submission" size="small"
                     @click="handleSubmit('formValidate')"
          >提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!--选择商品-->
    <goods-list ref="goodsList" @getProduct="getProduct"/>
  </div>
</template>

<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
import goodsList from '../goodsList'
import {
  productDetailApi
} from '@/api/product'
import { create, getSupplierSn } from '@/api/supplier'
import {
  roterPre
} from '@/settings'

const defaultObj = {
  product_id: '',
  store_name: '',
  image: '',
  supplier_sn: '',
  attrValue: [{
    image: '',
    price: null,
    cost: null,
    stock: null
  }],
  spec_type: 0,
  attr: []
}

const proOptions = [{
  name: '店铺推荐',
  value: 'is_good'
}]
export default {
  name: 'CombinationProductAdd',
  components: {
    goodsList
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          // return time.getTime() < Date.now();
          return time.getTime() > Date.now()
        }
      },
      timeVal: '',
      max_ficti_num: 0,
      dialogVisible: false,
      product_id: '',
      multipleSelection: [],
      optionsCate: {
        value: 'store_category_id',
        label: 'cate_name',
        children: 'children',
        emitPath: false
      },
      roterPre: roterPre,
      selectRule: '',
      checkboxGroup: [],
      recommend: proOptions,
      tabs: [],
      fullscreenLoading: false,
      props: {
        emitPath: false
      },
      propsMer: {
        emitPath: false,
        multiple: true
      },
      active: 0,
      OneattrValue: [Object.assign({}, defaultObj.attrValue[0])], // 单规格
      ManyAttrValue: [Object.assign({}, defaultObj.attrValue[0])], // 多规格
      ruleList: [],
      merCateList: [], // 商户分类筛选
      categoryList: [], // 平台分类筛选
      shippingList: [], // 发货时间
      guaranteeList: [], // 服务保障模板
      deliveryList: [],
      labelList: [], // 商品标签
      BrandList: [], // 品牌
      formValidate: Object.assign({}, defaultObj),
      maxStock: '',
      addNum: 0,
      singleSpecification: {},
      multipleSpecifications: [],
      formDynamics: {
        template_name: '',
        template_value: []
      },
      manyTabTit: {},
      manyTabDate: {},
      grid2: {
        lg: 10,
        md: 12,
        sm: 24,
        xs: 24
      },
      // 规格数据
      formDynamic: {
        attrsName: '',
        attrsVal: ''
      },
      isBtn: false,
      manyFormValidate: [],
      images: [],
      currentTab: 0,
      isChoice: '',
      combinationData: {
        ficti_status: 0,
        group_buying_rate: ''
      },
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24
      },
      loading: false,
      ruleValidate: {},
      attrInfo: {},
      keyNum: 0,
      extensionStatus: 0,
      isNew: false,
      previewVisible: false,
      previewKey: '',
      deliveryType: []
    }
  },
  computed: {
    attrValue() {
      const obj = Object.assign({}, defaultObj.attrValue[0])
      delete obj.image
      return obj
    },
    oneFormBatch() {
      const obj = [Object.assign({}, defaultObj.attrValue[0])]
      delete obj[0].bar_code
      return obj
    }
  },
  watch: {
    'formValidate.attr': {
      handler: function(val) {
        if (this.formValidate.spec_type === 1) this.watCh(val)
      },
      immediate: false,
      deep: true
    }
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route)
    if (this.$route.params.id && this.formValidate.spec_type === 1) {
      this.$watch('formValidate.attr', this.watCh)
    }
  },
  mounted() {
  },
  methods: {
    getSn() {
      getSupplierSn().then(res => {
        this.formValidate.supplier_sn = res.data.supplier_sn
      })
    },
    add() {
      this.$refs.goodsList.dialogVisible = true
    },
    getProduct(data) {
      this.formValidate.image = data.src
      this.product_id = data.id
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    watCh(val) {
      const tmp = {}
      const tmpTab = {}
      this.formValidate.attr.forEach((o, i) => {
        tmp['value' + i] = {
          title: o.value
        }
        tmpTab['value' + i] = ''
      })
      this.ManyAttrValue.forEach((val, index) => {
        const key = Object.values(val.detail).sort().join('/')
        if (this.attrInfo[key]) this.ManyAttrValue[index] = this.attrInfo[key]
      })
      this.attrInfo = {}
      this.ManyAttrValue.forEach((val) => {
        this.attrInfo[Object.values(val.detail).sort().join('/')] = val
      })
      this.manyTabTit = tmp
      this.manyTabDate = tmpTab
    },
    // 详情
    getInfo(id) {
      this.fullscreenLoading = true
      productDetailApi(id)
        .then(async(res) => {
          const info = res.data
          this.formValidate = {
            product_id: info.product_id,
            supplier_sn: '',
            store_name: info.store_name,
            image: info.image,
            attr: info.attr,
            spec_type: info.spec_type
          }
          this.timeVal = []
          if (this.formValidate.spec_type === 0) {
            this.OneattrValue = info.attrValue
            this.OneattrValue.forEach((val, i) => {
              delete val.image
              delete val.stock
              delete val.sales
              delete val.ot_price
              delete val.volume
              delete val.weight
              delete val.type
              delete val.extension_one
              delete val.extension_two
              delete val.svip_price
              this.$set(this.OneattrValue[i], 'xh_price', 0)
              this.$set(this.OneattrValue[i], 'cost_price', 0)
              this.$set(this.OneattrValue[i], 'stock_num', 0)
            })
            this.singleSpecification = JSON.parse(
              JSON.stringify(info.attrValue)
            )
            this.formValidate.attrValue = this.OneattrValue
          } else {
            this.ManyAttrValue = info.attrValue
            this.multipleSpecifications = JSON.parse(JSON.stringify(info.attrValue))
            this.ManyAttrValue.forEach((val, i) => {
              delete val.image
              delete val.stock
              delete val.sales
              delete val.ot_price
              delete val.volume
              delete val.weight
              delete val.type
              delete val.extension_one
              delete val.extension_two
              delete val.svip_price
              this.attrInfo[Object.values(val.detail).sort().join('/')] = val
              this.$set(this.ManyAttrValue[i], 'xh_price', 0)
              this.$set(this.ManyAttrValue[i], 'cost_price', 0)
              this.$set(this.ManyAttrValue[i], 'stock_num', 0)
            })
            this.multipleSelection = info.attrValue
            this.$nextTick(() => {
              info.attrValue.forEach((row) => {
                this.$refs.multipleSelection.toggleRowSelection(row, true)
              })
            })
            this.formValidate.attrValue = this.multipleSelection
          }
          this.fullscreenLoading = false
        })
        .catch((res) => {
          this.fullscreenLoading = false
          this.$message.error(res.message)
        })
    },
    handleSubmitUp() {
      if (this.currentTab-- < 0) this.currentTab = 0
    },
    handleSubmitNest1(name) {
      if (!this.formValidate.image) {
        this.$message.warning('请选择商品！')
        return
      } else {
        this.currentTab++
        if (!this.$route.params.id) this.getInfo(this.product_id)
      }
    },
    // 提交
    handleSubmit(name) {
      if (this.formValidate.supplier_sn === '') {
        this.$message.warning('请输入进货单号！')
        return
      }
      if (this.formValidate.spec_type === 1) {
        this.formValidate.attrValue = this.multipleSelection
      } else {
        this.formValidate.attrValue = this.OneattrValue
      }
      if (
        !this.formValidate.attrValue ||
        this.formValidate.attrValue.length === 0
      ) {
        this.$message.warning('请选择进货商品！')
        return
      }
      // 判断进货数量 不能为0
      let flag = false
      if (this.formValidate.spec_type === 1) {
        this.formValidate.attrValue.forEach((val) => {
          if (val.stock_num === 0) {
            flag = true
          }
        })
      }
      if (flag) {
        this.$message.warning('进货数量不能为0！')
        return
      }
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.fullscreenLoading = true
          this.loading = true
          const from = {
            product_id: this.formValidate.product_id,
            supplier_sn: this.formValidate.supplier_sn,
            text_json: this.formValidate.attrValue
          }
          console.log(from)
          create(from)
            .then(async(res) => {
              this.fullscreenLoading = false
              this.$message.success(res.message)
              this.$router.push({
                path: this.roterPre + '/supplier/supplier/supplier_add'
              })
              this.$refs[name].resetFields()
              this.loading = false
            })
            .catch((res) => {
              this.fullscreenLoading = false
              this.loading = false
              this.$message.error(res.message)
            })
        } else {
          if (
            !this.formValidate.image || !this.formValidate.supplier_sn || !this.formValidate.attrValue
          ) {
            this.$message.warning('请填写完整信息！')
          }
        }
      })
    },
    // 表单验证
    validate(prop, status, error) {
      if (status === false) {
        this.$message.warning(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.bg {
  z-index: 100;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

.goods_detail .goods_detail_wrapper {
  z-index: -10
}

.priceBox {
  /deep/ input {
    padding-right: 0;
  }
}

.sp100 {
  width: 100%;
}

.proCoupon {
  /deep/ .el-form-item__content {
    margin-top: 5px;
  }
}

.item_desc {
  color: #999;
  font-size: 12px;
}

.tabPic {
  width: 40px !important;
  height: 40px !important;

  img {
    width: 100%;
    height: 100%;
  }
}

.noLeft {
  /deep/ .el-form-item__content {
    margin-left: 0 !important;
  }
}

.tabNumWidth {
  /deep/ .el-input-number--medium {
    width: 121px !important;
  }

  /deep/ .el-input-number__increase {
    width: 20px !important;
    font-size: 12px !important;
  }

  /deep/ .el-input-number__decrease {
    width: 20px !important;
    font-size: 12px !important;
  }

  /deep/ .el-input-number--medium .el-input__inner {
    padding-left: 25px !important;
    padding-right: 25px !important;
  }

  /deep/ thead {
    line-height: normal !important;
  }

  /deep/ .el-table .cell {
    line-height: normal !important;
  }
}

.selWidth {
  width: 100%;
}

.selWidthd {
  width: 300px;
}

.selWidthd1 {
  width: 200px;
}

.button-new-tag {
  height: 28px;
  line-height: 26px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }
}

.btndel {
  position: absolute;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
  left: 46px;
  top: -4px;
}

.labeltop {
  /deep/ .el-form-item__label {
    float: none !important;
    display: inline-block !important;
    margin-left: 120px !important;
    width: auto !important;
  }
}
</style>
